package net.zoneland.zrdp.common.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import org.apache.commons.lang3.StringUtils;
import net.zoneland.zrdp.common.utils.StringUtilPlus;

/**
 * 防止XSS攻击的过滤器
 *
 * @author zonevue
 */
public class XssFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(XssFilter.class);
    /**
     * 排除链接
     */
    protected static final List<String> excludes = new ArrayList<>();

    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {
        final String tempExcludes = filterConfig.getInitParameter("excludes");
        if (StringUtils.isNotEmpty(tempExcludes)) {
            final String[] url = StringUtils.split(tempExcludes, ",");
            Collections.addAll(excludes, url);
        }
    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {

        final HttpServletRequest req = (HttpServletRequest) request;
        if (handleExcludeURL(req)) {
            chain.doFilter(request, response);
            return;
        }
        final XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
        chain.doFilter(xssRequest, response);
    }

    private boolean handleExcludeURL(final HttpServletRequest request) {
        final String url = request.getServletPath();

        return StringUtilPlus.matches(url, excludes);
    }

    @Override
    public void destroy() {
        LOGGER.debug("XssFilter destroy...");
    }
}
